package com.atguigu.tingshu.album.service.impl;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;


@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    //头像,封面文件上传
    @Override
    public String fileUpload(MultipartFile file) {
        //检查文件大小
        try {
            //获取图片
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                throw new GuiguException(400, "文件格式有误");
            }
            //图片格式
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();
            if (height > 1080 || width > 1080) {
                throw new GuiguException(400, "文件大小有误");
            }
        } catch (Exception e) {
            throw new GuiguException(400, "文件格式有误");
        }
        //3.将文件上传到MInIO
        //3.1 生成带有文件夹目录文件名称 形式：/日期/随机文件名称.后缀
        //日期
        try {
            //3.将文件上传到MInIO
            //3.1 生成带有文件夹目录文件名称 形式：/日期/随机文件名称.后缀
            //日期
            String folder = "/" + DateUtil.today();
            //随机文件名称
            String fileName = IdUtil.randomUUID();
            //文件后缀
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            //完成文件夹拼接
            String objName = folder + "/" + fileName + "." + extName;
            //3.2 调用minio客户对象上传文件方法
            String bucketName = minioConstantProperties.getBucketName();
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(objName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            //3.3 拼接上传文件在线路径地址
            return minioConstantProperties.getEndpointUrl() + "/" + bucketName + objName;
        } catch (Exception e) {
            throw new GuiguException(500, "文件上传失败");
        }

    }
}


